<template>
  <div class="shouj">

    <div id="container"></div>
    <div id="panel"></div> <!-- 添加面板 -->
    <div class="shuju">

      <ul class="infinite-list" v-infinite-scroll="load" style="overflow:auto">
        <div class="didian" v-for="rider in list">
          <span>{{ rider.startingPoint }}</span><br>
          <span>{{ rider.terminal }}</span>
          <button @click="showRoute(rider)">显示路线</button> <!-- 新增按钮 -->
        </div>
      </ul>
    </div>
    <van-button class="butt" @click="toCollect">

      >>>>到达目的地

      <!--        <span>29.17元</span>-->

    </van-button>


    <el-dialog width="100%" title="取消原因" :visible.sync="dialogFormVisible">
      <el-form :model="form">
        <h7>自己原因</h7>
        <van-dropdown-menu style="margin-bottom: 40px;">
          <van-dropdown-item v-model="form.ownReasons" :options="option1"/>
        </van-dropdown-menu>
        <h7>乘客原因</h7>
        <van-dropdown-menu style="margin-bottom: 40px;">
          <van-dropdown-item v-model="form.passengerReasons" :options="option2"/>
        </van-dropdown-menu>
        <h7>其他原因</h7>
        <van-cell-group inset>
          <van-field v-model="form.otherReasons" label="其他原因" placeholder="请输入原因"/>
        </van-cell-group>
        <!--      文件上传-->
        <el-upload
          action="/order/cancelorder/fileUpload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove">
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="form.fileList" alt="">
        </el-dialog>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="change">确 定</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import {ref} from 'vue';
import {createApp} from 'vue';
import {Popup} from 'vant';
import AMapLoader from "@amap/amap-jsapi-loader";
import axios from "axios";

window._AMapSecurityConfig = {
  // 安全密钥
  securityJsCode: "23a30393a855e07d2ba7621ac8e4e6d2",
};

export default {
  name: "HomeView",
  setup() {
    const value = ref('');

    const fileList = ref([]);

    const afterRead = (file) => {
      file.status = 'uploading';
      file.message = '上传中...';

      setTimeout(() => {
        file.status = 'failed';
        file.message = '上传失败';
      }, 1000);
    };
    const ownReasons = ref(0);
    const passengerReasons = ref(0);
    const option1 = [
      {text: '电量不足', value: 0},
      {text: '交通拥堵,无法按时抵达', value: 1},
      {text: '车辆故障', value: 2},
      {text: '身体不适', value: 3}
    ];
    const option2 = [
      {text: '多名乘客，无法乘坐', value: 0},
      {text: '乘客超时未达到出发点', value: 1},
      {text: '乘客物品超限', value: 2},
    ];

    return {
      option1,
      option2,
      fileList,
      afterRead,
    };
  },
  data() {
    return {
      // 地图实例
      dialogFormVisible: false,
      forms: {},
      radio: '',
      //乘车码弹框（默认：未开启）
      carcodeShow: false,
      //乘车码
      carcode: "",
      list: {},
      // 地图实例
      map: null,
      // 标记点
      marker: "",
      // 地址逆解析
      geoCoder: null,
      // 搜索提示
      AutoComplete: null,
      //缩放控件
      ToolBar: null,
      //地图放大镜
      HawkEye: null,
      // 搜索关键字
      keywords: "",
      // 位置信息
      form: {
        lng: "116.397427",
        lat: "39.909302",
        address: '',
      },
      // 搜索节流阀
      loading: false,
      // 搜索提示信息
      options: [],
      id: 0
    };
  },
  created() {
    this.initMap();
    this.getListSync(); // 修改为调用同步获取列表的方法
    this.id = sessionStorage.getItem("id")
  },
  methods: {
    toCollect() {
      this.$router.push("/collect");
    },
    change() {
      axios.post('/order/cancelorder/change', this.form).then(res => {
        if (res.data.code == 200) {
          this.dialogFormVisible = false;
          this.$message.success(res.data.message);
          this.$router.push("/shouye");
        } else {
          this.$message.error(res.data.message)
        }
        l
      })
    },
    qx() {
      this.dialogFormVisible = true;
      this.value = '';
    },
    fan() {
      this.$router.back(-1);
    },

    // 显示路线
    showRoute(rider) {
      const startingPoint = rider.startingPoint;
      const terminal = rider.terminal;

      // 获取起点和终点的经纬度
      this.getGeocode(startingPoint, terminal).then(({startLatLng, endLatLng}) => {
        // 计算两点之间的距离
        this.calculateDistance(startLatLng, endLatLng);

        // 绘制路线
        this.drawRoute(startLatLng, endLatLng);
      }).catch(error => {
        console.error("获取经纬度失败：", error);
      });
    },
    // 获取经纬度
    getGeocode(startingPoint, terminal) {
      return Promise.all([
        this.getLatLng(startingPoint),
        this.getLatLng(terminal)
      ]).then(([startLatLng, endLatLng]) => ({
        startLatLng,
        endLatLng
      }));
    },
    // 获取单个地址的经纬度
    getLatLng(address) {
      return new Promise((resolve, reject) => {
        this.geoCoder.getLocation(address, (status, result) => {
          if (status === 'complete' && result.info === 'OK') {
            const location = result.geocodes[0].location;
            resolve([location.lng, location.lat]);
          } else {
            reject(new Error('无法获取经纬度'));
          }
        });
      });
    },
    // 计算两点之间的距离
    calculateDistance(startLatLng, endLatLng) {
      AMapLoader.load({
        key: "b17513b156700f5d461409278e81ffa7",
        version: "2.0",
        plugins: ["AMap.Driving"]
      }).then((AMap) => {
        const driving = new AMap.Driving({
          map: this.map,
          panel: "panel"
        });

        driving.search(startLatLng, endLatLng, (status, result) => {
          if (status === 'complete') {
            console.log('驾车距离:', result.routes[0].distance, '米');
          } else {
            console.error('驾车搜索失败：', result);
          }
        });
      }).catch(e => {
        console.error(e);
      });
    },
    // 绘制路线
    drawRoute(startLatLng, endLatLng) {
      AMapLoader.load({
        key: "b17513b156700f5d461409278e81ffa7",
        version: "2.0",
        plugins: ["AMap.Driving"]
      }).then((AMap) => {
        const driving = new AMap.Driving({
          map: this.map,
          panel: "panel"
        });

        driving.search(startLatLng, endLatLng, (status, result) => {
          if (status === 'complete') {
            console.log('驾车搜索成功');
          } else {
            console.error('驾车搜索失败：', result);
          }
        });
      }).catch(e => {
        console.error(e);
      });
    },
    tomudidi() {
      this.$router.push('/destination')
    },
    tijiaocode() {
    },
    // 接到乘客
    handlePickup() {
      this.carcodeShow = true;
      this.carcode = "";
    },
    // 到达出发点
    handleArrive() {
      // 到达出发点按钮点击事件处理
      this.$router.push('/setOut')
      console.log('已到达出发点');
      // 这里可以添加具体的逻辑，如更新状态、发送请求等
    },
    // 根据手机号查询到司机id
    async findDriverByTel() {
      const tel = JSON.parse(localStorage.getItem('login'));
      const response = await axios.post('personal/personal/findByTel?tel=' + tel);
      this.driverInfo = response.data;
      console.log(this.driverInfo);
      return this.driverInfo;
    },
    async getListSync() {
      try {
        // 先获取司机信息
        const driverInfo = await this.findDriverByTel();
        // 再根据司机信息获取列表数据
        const response = await axios.get(`/jiedan/riderQueue/findAll2?did=${this.driverInfo.id}` + "&id=" + this.id);
        this.list = response.data;
      } catch (error) {
        console.error("获取数据失败：", error);
      }
      await axios.post(`/jiedan/riderQueue/updateOrderType?id=${this.id}`)
    },
    reset() {
      this.keywords = '';
      this.form = {
        lng: "119.793098",
        lat: "31.91243",
        address: '',
      }
      // 清除点
      this.removeMarker();
      // 标记点
      this.setMapMarker();
    },
    initMap() {
      AMapLoader.load({
        // 你申请的Key
        key: "b17513b156700f5d461409278e81ffa7",
        version: "2.0",
        // 需要用到的插件
        plugins: ["AMap.Geocoder", "AMap.AutoComplete", "AMap.ToolBar", "AMap.HawkEye", "AMap.Geolocation", "AMap.Scale"],
      })
        .then((AMap) => {
          this.map = new AMap.Map("container", {
            viewMode: "3D", //是否为3D地图模式
            zoom: 10, //初始化地图级别
            center: [this.form.lng, this.form.lat], //初始化地图中心点位置
          });
          //地址逆解析插件
          this.geoCoder = new AMap.Geocoder({
            city: "010", //城市设为北京，默认：“全国”
            radius: 1000, //范围，默认：500
          });
          // 搜索提示插件
          this.AutoComplete = new AMap.AutoComplete({city: "全国"});
          this.ToolBar = new AMap.ToolBar({
            position: {
              bottom: '210px',
              right: '35px'
            }
          });
          this.HawkEye = new AMap.HawkEye({
            position: {
              bottom: '110px',
              left: '35px'
            }
          });
          this.Geolocation = new AMap.Geolocation({
            position: {
              bottom: '20px',
              right: '20px'
            }
          });
          this.Scale = new AMap.Scale({
            position: {
              bottom: '20px',
              left: '20px'
            }
          });
          this.map.addControl(this.ToolBar);
          // 省略部分代码...
          // 清除点
          this.removeMarker();
          // 标记点
          this.setMapMarker();
          //点击获取经纬度;
          this.map.on("click", (e) => {
            // 获取经纬度
            this.form.lng = e.lnglat.lng;
            this.form.lat = e.lnglat.lat;
            // 省略部分代码...
          });
        })
        .catch((err) => {
          // 错误
        });
    },
    // 标记点
    setMapMarker() {
      // 省略部分代码...
      // 逆解析地址
      this.toGeoCoder();
      this.map.add(this.marker);
    },
    // 清除点
    removeMarker() {
      if (this.marker) {
        this.map.remove(this.marker);
      }
    },
    xingc() {
      this.$router.push("/Trip")
    },
    // 逆解析地址
    toGeoCoder() {
      let lnglat = [this.form.lng, this.form.lat];
      this.geoCoder.getAddress(lnglat, (status, result) => {
        if (status === "complete") {
          this.form.address = result.regeocode.formattedAddress;
        } else {
          this.form.address = '';
        }
      });
    },
    querySearchAsync(queryString, cb) {
      if (queryString) {
        this.AutoComplete.search(queryString, (status, result) => {
          if (status === 'complete') {
            this.options = result.tips;
            for (let i = 0; i < this.options.length; i++) {
            }
          } else {
            this.options = [];
          }
          cb(this.options);
        });
      } else {
        this.options = [];
        cb(this.options);
      }
    },
    handleSelect(val) {
      // 清空时不执行后面代码
      if (!val) {
        return;
      }
      this.form = {
        lng: val.location.lng,
        lat: val.location.lat,
        address: '',
      };
      // 省略部分代码...
    },
  },
  mounted() {
  },
};
</script>

<style scoped>
.shouj {
}

#container {
  width: 100%;
  height: 650px;
}

.shuju {
  //width: 100%;
  height: 100px;
  //margin-left: 10px;
  //float: left;
  //border-radius: 10px;
  //background-color: #FFFFFF;
  //background-color: #52b7fd;


  i {
    font-size: 40px;
    margin-top: 20px;
  }
}

.didian {
  width: 100%;
  height: 60px;

  span {
    font-size: 15px;
    line-height: 40px;
  }
}

ul {
  width: 200px;
  height: 100px;
  float: left;
}

.app {
  height: 120px;
  width: 100%;
  background-color: #FFFFFF;
  float: left;
}

.qu {
  font-size: 19px;
  float: left;
  margin-top: 10px;
  margin-left: 10px;
}

.xiao1 {
  float: left;
  margin-left: 10px;
}

.xiao2 {
  float: left;
  margin-left: 10px;
}

.butt {
  width: 80px;
  height: 30px;
  background-color: #52b7fd;
  color: #FFFFFF;
  border-radius: 5px;
  float: right;
  margin-top: -40px;
  margin-right: 10px;
  font-size: 12px;
}

.phones {
  width: 50px;
  height: 85px;
  float: left;
}

.shuzi {
  font-size: 35px;
}

.weihao {
  font-size: 20px;
}

.group {
  //width: 400px;
  //height: 80px;
  //background-color: #dedede;
  //float: left;
  //margin-left: 10px;
}

.daoda {
  width: 180px;
  height: 40px;
  background-color: #ff6700;
  border-radius: 30px;
  border: 0px;
  color: #FFFFFF;
  margin-right: 20px;
}

.infinite-list {
  width: 88%;
}

.butt {

  width: 370px;

  height: 60px;

  background-color: #4EA9CB;

  margin-top: 30px;

  color: #ffffff;


  span {

    margin-left: 80px;

  }

}

.jiedao {
  width: 180px;
  height: 40px;
  background-color: #00c7ff;
  border-radius: 30px;
  border: 0px;
  color: #FFFFFF;
}
</style>
